// 用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit";
import { getToken,setToken as _setToken, removeToken} from "@/utils";
import { getProfileAPI, loginAPI } from "@/apis/user";
const userStore = createSlice({
    name: 'user',
    initialState:
    {
        token: getToken() || '',
        userInfo:{}
    },
    reducers: {
        setToken(state,action){
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

// 解构出actionCreater函数
const {setToken,setUserInfo,clearUserInfo} = userStore.actions
// 发送异步请求
const fetchLogin = (loginFrom) =>{
    return async (dispatch)=>{
        // 1.发送异步请求
        const res = await loginAPI(loginFrom)
        // 2.提交同步action进行token的存入
        dispatch(setToken(res.data.token))
    }
}
// 发送异步请求获取个人信息
const fetchUserInfo = () =>{
    return async (dispatch)=>{
        // 1.发送异步请求
        const res = await getProfileAPI()
        // 2.提交同步action进行用用户信息的存入
        dispatch(setUserInfo(res.data))
    }
}

// 获取reducer函数
const reducer = userStore.reducer
export {fetchLogin,fetchUserInfo,setToken,clearUserInfo}
export default reducer